package com.rzico.sbl.ui.mine

import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityShopBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.MasterData
import com.rzico.sbl.model.QRType
import com.rzico.sbl.ui.ScanActivity
import com.rzico.sbl.viewmodel.ShopViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.conditionElse
import com.xinnuo.common.extend.conditionIf
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.extend.oneTouch
import com.xinnuo.common.extend.startActivityEx
import com.xinnuo.common.helper.getBoolean
import com.xinnuo.common.helper.getString
import com.xinnuo.common.helper.putShared
import com.xinnuo.common.view.FullyLinearLayoutManager
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.showTimeOpenDialog
import com.xinnuo.common_ui.utils.subscribeByFinally
import com.xinnuo.objectbox.equalString
import com.xinnuo.objectbox.getBox
import com.xinnuo.objectbox.getBoxEuery
import com.xinnuo.objectbox.model.AppLoginData
import com.xinnuo.objectbox.model.AppLoginData_
import com.xinnuo.objectbox.model.UserLoginData
import com.xinnuo.objectbox.model.UserLoginData_
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONObject

class ShopActivity : BaseActivity(R.layout.activity_shop) {

    private val mBinding by lazy { ActivityShopBinding.bind(getRootView()) }

    private lateinit var mInitJson: JSONObject
    private var mUserData: UserLoginData? = null
    private var mInitSHour: Int = 0
    private var mInitSMinute: Int = 0
    private var mInitEHour: Int = 0
    private var mInitEMinute: Int = 0

    override fun getViewModel() = get<ShopViewModel>()

    override fun initData() {
        initTitle(title = "我的店铺")

        initLayout()

        getData()
    }

    private fun initLayout() {
        mBinding
            .shopList
            .apply {
                isNestedScrollingEnabled = false
                layoutManager = FullyLinearLayoutManager(getIContext())

                addItemDecoration(SpaceTBDecoration(hasHeader = false))

                mAdapter = SlimAdapter.creator()
                    .register<MasterData>(R.layout.item_shop_list) { jector, bean, index ->
                        jector.apply {
                            text(R.id.item_shop_title, bean.name)
                            text(R.id.item_shop_name, "${bean.linkman}  ${bean.telephone}")
                            text(R.id.item_shop_adress, bean.address)

                            clicked(R.id.item_shop_print) {
                                if (bean.u.isNullOrEmpty()
                                    || bean.p.isNullOrEmpty()
                                ) {
                                    startActivityEx<ScanActivity>(
                                        "mode" to QRType.PRINT,
                                        "from" to "shop",
                                        "shopId" to bean.id
                                    )
                                } else {
                                    startActivityEx<ShopDeviceActivity>(
                                        "shopId" to bean.id,
                                        "account" to bean.u,
                                        "pwd" to bean.p
                                    )
                                }
                            }

                            clicked(R.id.item_shop_modify) {
                                startActivityEx<ShopModifyActivity>(
                                    "title" to "修改店铺",
                                    "status" to "edit",
                                    "shopId" to bean.id
                                )
                            }

                            longClicked {
                                shopDelete(bean.id, index)
                                true
                            }
                        }
                    }
                    .attachTo(this)
            }
    }

    override fun initListener() {
        val uid = getBoxEuery<AppLoginData>()
            .equal(AppLoginData_.isLogin, true)
            .build()
            .findFirst()
            ?.uid ?: ""

        mUserData =
            getBoxEuery<UserLoginData>()
                .equalString(UserLoginData_.uid, uid)
                .build()
                .findFirst()

        mBinding.apply {
            mInitJson = JSONObject(getString("configJson"))
            mInitSHour = mInitJson.optInt("startWork")
            mInitSMinute = mInitJson.optInt("startMinute")
            mInitEHour = mInitJson.optInt("endWork")
            mInitEMinute = mInitJson.optInt("endMinute")

            if (mInitSHour < 0) mInitSHour = 0
            if (mInitSMinute < 0) mInitSMinute = 0
            if (mInitEHour < 0) mInitEHour = 0
            if (mInitEMinute < 0) mInitEMinute = 0

            showShopOpenTime()
            shopWitch.isChecked =
                getBoolean("isOpen")
                    .apply {
                        conditionElse(
                            actionTrue = { shopExpand.expand() },
                            actionFalse = { shopExpand.collapse() }
                        )
                    }
            shopMobile.isChecked =
                mUserData?.let { it.callTelStatus == 1 } ?: false
            shopSecret.isChecked =
                mUserData?.let { it.privacyStatus == "on" } ?: true

            shopWitch.oneTouch {
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.shopPae,
                        onSuccess = {
                            shopWitch.isChecked = !it.toBoolean()

                            shopWitch.isChecked
                                .conditionElse(
                                    actionTrue = { shopExpand.expand() },
                                    actionFalse = { shopExpand.collapse() }
                                )

                            putShared("isOpen", !it.toBoolean())
                        }
                    )
            }

            shopTimeLl.oneClick {
                showTimeOpenDialog(
                    initLHour = mInitSHour,
                    initLMinute = mInitSMinute,
                    initRHour = mInitEHour,
                    initRMinute = mInitEMinute
                ) { s1, s2, e1, e2, start, end ->
                    mInitJson.put("startWork", s1)
                    mInitJson.put("startMinute", s2)
                    mInitJson.put("endWork", e1)
                    mInitJson.put("endMinute", e2)

                    getViewModel()
                        .request(
                            requestUrl = BaseUrl.shopSts,
                            params = arrayOf(
                                "shippingConfig" to mInitJson.toString()
                            ),
                            onSuccess = {
                                showToast("修改成功！")

                                mInitSHour = s1
                                mInitSMinute = s2
                                mInitEHour = e1
                                mInitEMinute = e2
                                shopTime.text = "$start - $end"
                                // 店铺时间配置
                                putShared("configJson", mInitJson.toString())
                            }
                        )


                }
            }

            shopMobile.oneTouch {
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.shopSts,
                        params = arrayOf(
                            "callOrder" to conditionIf(
                                shopMobile.isChecked,
                                0,
                                1
                            )
                        ),
                        onSuccess = {
                            shopMobile.isChecked = !shopMobile.isChecked

                            mUserData?.let {
                                it.callTelStatus =
                                    conditionIf(
                                        shopMobile.isChecked,
                                        1,
                                        0
                                    )

                                getBox<UserLoginData>().put(it)
                            }

                            putShared(
                                "incomeStatus",
                                conditionIf(
                                    shopMobile.isChecked,
                                    "1",
                                    "0"
                                )
                            )
                        }
                    )
            }

            shopSecret.oneTouch {
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.shopSts,
                        params = arrayOf(
                            "privacyStatus" to conditionIf(
                                shopSecret.isChecked,
                                "off",
                                "on"
                            )
                        ),
                        onSuccess = {
                            shopSecret.isChecked = !shopSecret.isChecked

                            mUserData?.let {
                                it.privacyStatus =
                                    conditionIf(
                                        shopSecret.isChecked,
                                        "on",
                                        "off"
                                    )

                                getBox<UserLoginData>().put(it)
                            }

                            putShared(
                                "privacyStatus",
                                conditionIf(
                                    shopSecret.isChecked,
                                    "on",
                                    "off"
                                )
                            )
                        }
                    )
            }

            btAdd.oneClick {
                startActivityEx<ShopModifyActivity>(
                    "title" to "添加店铺",
                    "status" to "add"
                )
            }
        }

        observe<String>("shopList") { getData() }
    }

    /**
     * 设置店铺营业时间
     */
    private fun showShopOpenTime() {
        val hintLHour = "%02d".format(mInitSHour)
        val hintLMinute = "%02d".format(mInitSMinute)
        val hintRHour = "%02d".format(mInitEHour)
        val hintRMinute = "%02d".format(mInitEMinute)

        mBinding.shopTime.text =
            "$hintLHour:$hintLMinute - ${
                when {
                    mInitSHour > mInitEHour -> "次日$hintRHour:$hintRMinute"
                    mInitSHour == mInitEHour
                            && mInitSMinute >= mInitEMinute -> "次日$hintRHour:$hintRMinute"

                    else -> "$hintRHour:$hintRMinute"
                }
            }"
    }

    /**
     * 删除店铺
     */
    private fun shopDelete(shopId: String, index: Int) {
        showHintDialog(
            title = "删除店铺",
            hint = "确定要删除该店铺吗？",
            sure = "删除",
            onSure = {
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.shopDel,
                        params = arrayOf("shopId" to shopId),
                        onSuccess = {
                            showToast("店铺删除成功！")

                            mList.removeAt(index)
                            mAdapter.apply {
                                notifyItemRemoved(index)
                                notifyItemRangeChanged(index, mList.size - index)
                            }
                        }
                    )
            }
        )
    }

    /**
     * 店铺列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .shopList()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = { list ->
                    mList.clear()
                    mList.addItems(list)
                    mAdapter.setDataList(mList)
                }
            )
    }

}